<!-- 点击事件设置 -->
<template>
    <div class="si-click-event">
        <el-button size="large" class="add-btn" @click="onAddEvent">
            {{ title }}
        </el-button>

        <div v-if="!!events.length" class="event-content">
            <si-collapse-group
                v-model="events"
                is-draggable
                is-delete
                :accordion="false"
                :node-title="data => getEventText(data)"
            >
                <template #right="{ element, index, buttonClass }">
                    <el-icon title="设置" :class="buttonClass" @click.stop="onEditEvent(element, index)"><icon-setting /></el-icon>
                </template>
                <template #item="{ element, index }">
                    <div v-if="isLinkEvent(element)" class="content-row">
                        <div class="content-row-title">传入页面参数</div>
                        <link-param :event-data="element" />
                    </div>
                    <div v-if="isFunctionEvent(element)" class="content-row">
                        <function-preview :event-data="element" />
                    </div>
                </template>
            </si-collapse-group>
        </div>

        <el-dialog
            v-model="showEventDialog"
            width="820px"
            top="65px"
            :title="title"
            :close-on-click-modal="false"
            append-to-body
            destroy-on-close
        >
            <div class="click-event-dialog">
                <el-tabs
                    :modelValue="eventType"
                    class="demo-tabs"
                    @tab-click="({ paneName }) => onEventTypeChange(paneName)"
                >
                    <el-tab-pane label="页面" name="link">
                        <link-setting ref="linkSetting" :event-data="currentEvent" />
                    </el-tab-pane>
                    <el-tab-pane label="功能" name="function">
                        <function-setting ref="functionSetting" :event-data="currentEvent" />
                    </el-tab-pane>
                </el-tabs>
            </div>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="onCancel">取消</el-button>
                    <el-button type="primary" :disabled="disabledConfirmBtn" @click="onConfirm">确认</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script>
import { defineComponent, toRefs, ref, computed, nextTick, onMounted } from 'vue'
import { useEditStore } from '@/store'
import { deepClone } from '@/libs/tools'
import useClickEvents from './composables/clickEvents'
import LinkSetting from './components/link-setting'
import LinkParam from './components/link-setting/components/link-param'
import FunctionSetting from './components/function-setting'
import FunctionPreview from './components/function-setting/components/function-preview'
import { onCloseEvent } from './events'
import SiCollapseGroup from '../si-collapse-group'
export default defineComponent({
    name: 'SiClickEvent',
    components: {
        LinkSetting,
        LinkParam,
        FunctionSetting,
        FunctionPreview,
        SiCollapseGroup
    },
    props: {
        // 标题
        title: {
            type: String,
            default: '添加点击事件'
        },
        // 事件对象
        event: {
            type: Object,
            // default: () => ({})
        }
    },
    emits: [
        'update:event'
    ],
    setup(props, { emit }) {
        const { title, event } = toRefs(props)

        const editStore = useEditStore()

        const {
            clickEvents,
            deleteClickEvent
        } = useClickEvents()

        const showEventDialog = ref(false)
        // 事件类型(link页面，function功能)
        const eventType = ref('link')
        // 当前事件数据
        const currentEvent = ref({}) // 当前事件数据
        const currentEventIndex = ref(-1) // 当前事件索引

        const linkSetting = ref(null)
        const functionSetting = ref(null)

        const cataDataPageFlat = computed(() => editStore.cataDataPageFlat)

        // 事件列表
        const events = computed({
            get: () => event.value?.events || [],
            set: val => event.value.events = val
        })

        // 确认按钮禁用状态
        const disabledConfirmBtn = computed(() => {
            let disabledStatus = false
            if (eventType.value === 'link') {
                const action = currentEvent.value.action
                const pageRouter = currentEvent.value['inner-page-link']
                if (!pageRouter) {
                    // 跳转页为空
                    disabledStatus = true
                } else if (!(!!action && !!clickEvents.link.some(item => item.value === action))) {
                    // 设置的跳转页面类型不存在
                    disabledStatus = true
                }
            } else if (eventType.value === 'function') {
                // 
            }
            return disabledStatus
        })

        onMounted(() => {
            if (!event.value) emit('update:event', {})
        })

        // 添加点击事件
        const onAddEvent = () => {
            showEventDialog.value = true
            currentEventIndex.value = -1
            onOpen()
        }

        // 修改点击事件
        const onEditEvent = (data, index) => {
            showEventDialog.value = true
            currentEventIndex.value = index
            onOpen(data)
        }

        const onOpen = (data = {}) => {
            const clickEvent = getClickEvent(data.action)
            if (!!clickEvent.type) {
                eventType.value = clickEvent.type
                currentEvent.value = deepClone(Object.assign({}, clickEvent.data.addData, data))
            } else {
                eventType.value = 'link'
                currentEvent.value = deepClone(data)
            }
            if (eventType.value === 'link') {
                nextTick(() => linkSetting.value.init())
            } else if (eventType.value === 'function') {
                nextTick(() => functionSetting.value.init())
            }
            // 接收关闭弹窗事件
            onCloseEvent(() => {
                showEventDialog.value = false
            })
        }

        // 获取事件文本
        const getEventText = data => {
            if (!data.action) return ''
            let eventTypeStr = ''
            let eventContentStr = ''
            const clickEvent = getClickEvent(data.action)
            if (clickEvent.type === 'link') {
                eventTypeStr = '页面'
                // 获取页面路径 (页面组 > 页面名称)
                const pageHierarchy = cataDataPageFlat.value?.[data['inner-page-link']]?.hierarchy || []
                if (pageHierarchy?.length > 0) {
                    eventContentStr = `${pageHierarchy[0].group} > ${pageHierarchy[pageHierarchy.length - 1].name}`
                }
            } else if (clickEvent.type === 'function') {
                eventTypeStr = '功能'
                eventContentStr = clickEvent.data.label
            }
            return `${eventTypeStr}：${eventContentStr}`
        }
        // 是否是页面跳转事件
        const isLinkEvent = data => {
            return clickEvents.link.find(item => item.value === data.action)
        }
        // 是否是功能事件
        const isFunctionEvent = data => {
            return clickEvents.function.find(item => item.value === data.action)
        }

        // 获取指定action对应的数据
        const getClickEvent = action => {
            let data = {}
            Object.keys(clickEvents).forEach(key => {
                const findAction = clickEvents[key].find(item => item.value === action)
                if (!!findAction) {
                    data = {
                        type: key,
                        data: findAction
                    }
                }
            })
            return data
        }

        // 切换事件类型
        const onEventTypeChange = type => {
            if (type === eventType.value) return
            eventType.value = type
            
            const clickEvent = getClickEvent(currentEvent.value.action)
            if (clickEvent.type === type) {
                currentEvent.value = deepClone(Object.assign({}, clickEvent.data.addData, currentEvent.value))
            } else {
                const newEvent = deepClone(currentEvent.value)
                onDeleteEvent(newEvent)
                if (type === 'link') {
                    // 
                } else if (type === 'function') {
                    currentEvent.value = deepClone(Object.assign({}, newEvent, clickEvents.function[0].addData))
                }
            }
        }

        // 删除事件
        const onDeleteEvent = data => {
            deleteClickEvent(data)
        }

        // 取消
        const onCancel = () => {
            showEventDialog.value = false
        }
        // 确认
        const onConfirm = () => {
            if (eventType.value === 'function') {
                const checkFun = clickEvents.function.find(item => item.value === currentEvent.value.action)?.checkFun
                if (!!checkFun && !checkFun(currentEvent.value)) {
                    return
                }
            }
            if (currentEventIndex.value === -1) {
                if (!events.value.length) events.value = []
                events.value.push(currentEvent.value)
            } else {
                events.value[currentEventIndex.value] = currentEvent.value
            }
            emit('update:event', event.value)
            showEventDialog.value = false
        }
        
        return {
            title,
            event,
            events,
            showEventDialog,
            eventType,
            currentEvent,
            disabledConfirmBtn,

            linkSetting,
            functionSetting,

            getEventText,
            isLinkEvent,
            isFunctionEvent,

            onAddEvent,
            onEditEvent,
            onOpen,
            onEventTypeChange,
            onDeleteEvent,

            onCancel,
            onConfirm
        }
    }
})
</script>

<style lang="less" scoped>
@import './si-click-event.less';
</style>